define(
	["input", "glMatrix"],
	function(input) {
		return {
			create : function(ccam) {
				
				var _inst 		= null;
				var _ZOOM_BTN 	= ('Q').charCodeAt(0);
				var _ROT_BTN 	= 17; //ctrl
			
				function _updateCamPos() {	
					//Compute position
					var cosRot = Math.cos(_inst.rotation);
					var sinRot = Math.sin(_inst.rotation);
					var cosEle = Math.cos(_inst.elevation);
					var sinEle = Math.sin(_inst.elevation);
					var x = _inst.distance * sinRot * sinEle + _inst.target[0];
					var y = _inst.distance * cosEle + _inst.target[1];
					var z = _inst.distance * sinEle * cosRot + _inst.target[2];
					
					//Set the position
					_inst.cam.pos[0] = x;
					_inst.cam.pos[1] = y;
					_inst.cam.pos[2] = z;
					
					//Update the camera
					_inst.cam.update();
				};
				
				function _updateBasedOnInput(ttimer) {
					if(input.state() == 2) {
						
						//distance
						if(input.shiftKey() || input.isPressed(_ZOOM_BTN)) {
							_inst.distance += ttimer.lastDelta() * input.deltaPos[1] * 50;
							_inst.distance = Math.min(400, Math.max(5, _inst.distance)); //cap
						}
						
						//rot and elevation
						else if(input.isPressed(_ROT_BTN)) {
							_inst.rotation += ttimer.lastDelta() * input.deltaPos[0];
							_inst.elevation -= ttimer.lastDelta() * input.deltaPos[1];
							_inst.elevation = Math.min(Math.PI * 0.48, Math.max(Math.PI * 0.02, _inst.elevation)); //cap
						}				
						
						//target position
						else {
							var t = _inst.target;
							var c = _inst.cam;
							var temp = vec3.create();
							var dx = vec3.scale(c.right, ttimer.lastDelta() * input.deltaPos[0] * 50, temp);
							vec3.add(t, dx);
							var dz = vec3.scale(c.forward, 1, temp);
							dz[1] = 0;
							vec3.normalize(dz);
							vec3.scale(dz, ttimer.lastDelta() * input.deltaPos[1] * 50);
							vec3.add(t, dz);
						}
					}
				};
			
				return _inst = {
					cam: ccam,
					target: ccam.target,
					distance: 10,
					elevation: Math.PI * 0.25,
					rotation: Math.PI * 0,
					update: function(timer) {	
						_updateBasedOnInput(timer);
						_updateCamPos();
					}
				};
			}
		};
	}
);
